var APIURL = "http://haoyunsoon.duapp.com";

localStorage.setItem("userId","4");
localStorage.setItem("userName","测试用户");

// var userId = localStorage.getItem("userId");
// var userName = localStorage.getItem("userName");
var indexUrl = "http://www.zonboapp.com";
var err_txt = "操作失败";
//星星
function getLevel(score){
	var pc_inline = is_pc() ? "inline-block" : "";
	var scoreStr = '<p class="level '+pc_inline+'">';
	var averageScore = parseInt(score);
	for(var m = 0;m < averageScore;m++){
		scoreStr += '<i class="full"></i>'
	}
	for(var n = 0;n < 5-averageScore;n++){
		scoreStr += '<i></i>'
	}
	scoreStr += '</p>';
	return scoreStr;
}

function userId() {
  return localStorage.getItem("userId");
}

function userName() {
  return localStorage.getItem("userName");
}

function getCLientType() {
  return localStorage.getItem("clientType");
}

function getSearchValue(v,select){
    var ha,haa;
    ha = location.search.substr(1);
    if( !(new RegExp("v").test(ha)) ){
      ha = localStorage.getItem(select || "pageparam");
    }
    ha = ha.split("&");
    for(var i = 0 ;i < ha.length;i++){
        haa = ha[i].split("=");
        if(v == haa[0]){
            return decodeURIComponent(haa[1])
        }
    }
}

function is_pc() {
    var sUserAgent = navigator.userAgent.toLowerCase();
    var bIsIpad = sUserAgent.match(/ipad/i) == "ipad";
    var bIsIphoneOs = sUserAgent.match(/iphone os/i) == "iphone os";
    var bIsMidp = sUserAgent.match(/midp/i) == "midp";
    var bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4";
    var bIsUc = sUserAgent.match(/ucweb/i) == "ucweb";
    var bIsAndroid = sUserAgent.match(/android/i) == "android";
    var bIsCE = sUserAgent.match(/windows ce/i) == "windows ce";
    var bIsWM = sUserAgent.match(/windows mobile/i) == "windows mobile";
    if (!(bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM) ){
        return true
    }
};

function tips(str){
    if($(".tips")[0]){
        $(".tips").remove();
    };
    $("body").append('<div class="tips"><span>'+str+'</span></div>');
    $(".tips").show();
    setTimeout(function(){
        $(".tips").fadeOut();
    },1500)


}

//加载引导页面
function loadGuide(always){
    $.get("tpl/download-guide.html",function(html){
        var guide_close = localStorage.getItem("guide_close");
        var guideClock = 3600000; //一个小时
        if(!guide_close || always){
          guideHandle();         
        }else if(guide_close && (new Date().getTime() - guide_close) >= guideClock){
          guideHandle()
        };
        function guideHandle(){
          $("body").append(html);
          var url = "http://a.app.qq.com/o/simple.jsp?pkgname=com.wyfc.writenovel";          
          if(getCLientType() == "lovenovel"){
            url = "http://a.app.qq.com/o/simple.jsp?pkgname=com.wyfc.lovenovel"; 
            $(".download-guide .item").hide().eq(1).show();
          }
          $(".download-guide .download-url").attr("href",url);
          $(".download-guide .layermend").one("click",function(){
              $(this).parent().parent().remove();
              localStorage.setItem("guide_close",new Date().getTime())
          }) 
        }

    })
}

//加载浏览器升级引导页面
function checkBroswer(){
    if(localStorage)return;
    $.get("tpl/check-broswer.html",function(html){
        $("body").append(html);
        $(".check-broswer .check-broswer-con .check-broswer-item").hover(function(){
            $(this).find(".item-img").stop().animate({top:"150px"},300)
        },function(){
            $(this).find(".item-img").stop().animate({top:"0"},300)
        })
    })
}

function changeBackground(){
    $("body").append('<a href="javascript:;" class="change-bg black">夜晚模式</a>')
    var changebg = $(".change-bg");
    if(localStorage.change){
        changebg.addClass("toblank").text("白天模式");
        $("body").addClass("blank");
    }
    changebg.on("click",function(){
        $("body").toggleClass("blank");
        if(!$(this).hasClass("toblank")){
            $(this).addClass("toblank").text("白天模式");
            localStorage.change = "true"
        }else{
            $(this).removeClass("toblank").text("夜晚模式");
            delete localStorage.change
        }
    })
}

function logoutHandle(){
    $("#logout").on("click",function(){
        localStorage.removeItem("userId");
        localStorage.removeItem("userName");
        gotoLogin();
    })
}

function checkLog(){    
    if(!userId() || !userName()){
        gotoLogin()
    }
}

function gotoLogin(){
    window.location.href = "login.html";
}

function baseLoad(){
    $("body").append('<div class="loading"><span></span></div>');
}
function hideBaseLoad(){
    $(".loading").remove();
}

function setTitle(tle){
    $(".head-tle .txt").text(tle)
}

function createBarBread(arr){
    var str = "";
    var len = arr.length;
    for(var i = 0; i < len; i++){
        if(i == 0){         
          str += '<a href="javascript:;" style="cursor:text">'+arr[i].title+'</a>'
        }else if( i == (len - 1) ){
          str += '<i>></i><span>'+arr[i].title+'</span>'
        }else{
          var urlParam = arr[i].urlparam || "";
          str += '<i>></i><a href="javascript:;" data-url="'+arr[i].url+'" data-param="'+urlParam+'">'+arr[i].title+'</a>';
        }
    }
    $(".bar-bread").html(str).on("click","a",function(){
      localStorage.setItem("pageparam_detail",$(this).attr("data-param"));
      var url = $(this).attr("data-url");
      if(url){
        window.location.href = url;
      }
    });

}

$(function(){
    var domain = location.hostname;
    $(".footer em").html(domain);
    if(userId() && userName()){
        $(".content > .hd").append(
            '<div class="fr custom-info-box"><span class="ellipsis_1" id="nickName">'+userName()+'</span><a href="javascript:;" id="logout">[退出]</a></div>'
            );
    }
    logoutHandle();
    changeBackground();
    checkBroswer();
})

//文本框输入TAB建缩进，回车键换行缩进

/*------selection operations-------*/
function insertAtCursor(obj, txt) {
 obj.focus();
 //IE support
 if (document.selection) {
   sel = document.selection.createRange();
   sel.text = txt;
 }
 //MOZILLA/NETSCAPE support
 else {
   var startPos = obj.selectionStart;
   var scrollTop = obj.scrollTop;
   var endPos = obj.selectionEnd;
   obj.value = obj.value.substring(0, startPos) + txt + obj.value.substring(endPos, obj.value.length);
   startPos += txt.length;
   obj.setSelectionRange(startPos, startPos);
   obj.scrollTop = scrollTop;
 }
}
function getCaretPos(ctrl) {
   var caretPos = 0;
   if (document.selection) {
   // IE Support
   var range = document.selection.createRange();
   // We'll use this as a 'dummy'
   var stored_range = range.duplicate();
   // Select all text
   stored_range.moveToElementText( ctrl );
   // Now move 'dummy' end point to end point of original range
   stored_range.setEndPoint( 'EndToEnd', range );
   // Now we can calculate start and end points
   ctrl.selectionStart = stored_range.text.length - range.text.length;
   ctrl.selectionEnd = ctrl.selectionStart + range.text.length;
   caretPos = ctrl.selectionStart;
   } else if (ctrl.selectionStart || ctrl.selectionStart == '0')
   // Firefox support
       caretPos = ctrl.selectionStart;
   return (caretPos);
}

function getCurrentLineBlanks(obj) {
 var pos = getCaretPos(obj);
 var str = obj.value;
 var i = pos-1;
 while (i>=0) {
   if (str.charAt(i) == '\n')
     break;
   i--;
 }
 i++;
 var blanks = "";
 while (i < str.length) {
   var c = str.charAt(i);
   if (c == ' ' || c == '\t')
     blanks += c;
   else
     break;
   i++;
 }
 return blanks;
}

function set_tab_indent_for_textareas() {
 /* set all the tab indent for all the text areas */
 $("body").on("keydown","textarea",function(eve){
     if (eve.target != this) return;
     if (eve.keyCode == 13)
       last_blanks = getCurrentLineBlanks(this);
     else if (eve.keyCode == 9) {
       eve.preventDefault();
       insertAtCursor(this, "　　");
       this.returnValue = false;
     }  
 })
 // .on("keyup","textarea",function(eve){
 //     if (eve.target == this && eve.keyCode == 13)
 //         insertAtCursor(this, "　　");  
 // })
}
